package com.yanyeori.utilscollection.aliyunoss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yanyeori.framework.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * ALIYUN OSS文件存储
 *
 * @author chenkuan
 * @since 2022/9/29 16:05
 */
@Component
public class OssFileUtil {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OssConfig ossConfig;

    /**
     * 文件上传接口
     *
     * @param file 上传的文件
     * @return 下载文件名
     */
    public String uploadFile(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        //创建OSSClient实例
        OSS ossClient = buildOSSClient();
        //调用oss实现上传，bucket名称+文件名称+输入流
        ossClient.putObject(ossConfig.getBucketName(), fileName, file.getInputStream());
        //关闭OSSClient
        ossClient.shutdown();
        logger.info("file[{}] upload to OSS success", fileName);
        //桶为公共读则直接生成下载外链，若为私有则生成下载接口参数
        if (ossConfig.isPublicRead()) {
            return StringUtil.format("{}{}.{}/{}", ossConfig.getHttp(), ossConfig.getBucketName(), ossConfig.getEndpoint(), fileName);
        } else {
            return fileName;
        }
    }

    /**
     * 文件下载接口
     *
     * @param fileName 下载文件名
     * @return 下载链接
     */
    public String downloadFile(String fileName) {
        //创建OSSClient实例
        OSS ossClient = buildOSSClient();
        Date expiration = new Date(System.currentTimeMillis() + ossConfig.getUrlExpiration() * 1000);
        return ossClient.generatePresignedUrl(ossConfig.getBucketName(), fileName, expiration).toString();
    }

    /**
     * 创建OSSClient实例
     */
    private OSS buildOSSClient() {
        return new OSSClientBuilder().build(ossConfig.getHttp() + ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    }
}
